import http from "@ohos.net.http";

export class HttpRequest {
  private url: string
  options: http.HttpRequestOptions;
  private currentRequest?: http.HttpRequest;

  /**
   * HttpRequest构造器
   */
  constructor() {
    this.url = ''
    this.options = {
      method: http.RequestMethod.POST,
      header: { 'Content-Type': 'text/xml' },
      expectDataType: http.HttpDataType.STRING,
      usingCache: true,
      priority: 1,
      readTimeout: 60000,
      connectTimeout: 60000,
      usingProtocol: http.HttpProtocol.HTTP1_1,
    }
  }

  /**
   * 设置请求路径
   * @param url 路径
   */
  setUrl(url: string) {
    this.url = url
  }


  /**
   * 设置请求参数
   * @param extraData 参数
   */
  setExtraData(extraData: Object) {
    this.options.extraData = extraData
  }

  /**
   * 设置请求头
   * @param header 请求头
   */
  setHeader(header: Object) {
    console.log('header', JSON.stringify(header))
    this.options.header = header
  }

  /**
   * 设置请求配置项
   * @param option 配置项
   */
  setOptions(option: Object): void {
    this.options = option
  }


  /**
   * 流式请求  API 9 不可用
   * @param getData 传入回调函数获取数据
   * @returns
   */
  /*requestInStream(getData) {
    return new Promise((resolve,reject)=>{
      let httpRequest = http.createHttp()
      httpRequest.on('dataReceive', function (data) {
        getData(data)
      });
      // httpRequest.on('dataReceiveProgress', function (data) {
      //   getData(data)
      // });
      httpRequest.requestInStream(this.url, this.options,(err,data)=>{
        if(!err){
          httpRequest.destroy()
          httpRequest.off('dataReceive')
          httpRequest.off('dataReceiveProgress')
          resolve(data)
        }else {
          httpRequest.destroy()
          reject(err)
        }
      });
    })
  }*/


  /**
   * 普通请求
   * @returns Promise 请求响应对象
   */
  async request(option?: http.HttpRequestOptions): Promise<http.HttpResponse> {
    let dstOptions: http.HttpRequestOptions = {
      ...this.options,
      ...option,
    }
    let httpRequest: http.HttpRequest = http.createHttp();
    this.currentRequest = httpRequest;
    httpRequest.on('headersReceive', (header: Object) => {
      console.info('header: ' + JSON.stringify(header));
    });
    let httpResp: http.HttpResponse = await httpRequest.request(this.url, dstOptions );
    httpRequest.off('headersReceive')
    httpRequest.destroy();
    return httpResp;
  }

  public destroy():void{
    this.currentRequest?.destroy();
  }
}

export default new HttpRequest();